﻿using BridgeWeChat.Model;
using BridgeWebSystemLib.Core;
using BridgeWebSystemLib.Core.Net;
using BridgeWebSystemLib.Core.Util;
using Org.BouncyCastle.Ocsp;
using System;
using System.Collections.Generic;
using System.Text;
using System.Web;

namespace WeChatCommon.MP.TemplateMessage
{
    public abstract class AbstractTemplateMessageProcess : ITemplateMessageProcess
    {
        public readonly string WeChatHttpUrl = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token={0}";
        public string AccessToken 
        {
            get { return _accessToken; } 
        }
        private string _accessToken;

        private WeChatTemplateMessageRequest _requestParam;
        public AbstractTemplateMessageProcess(WeChatTemplateMessageRequest requestParam)
        {
            _requestParam = requestParam;
        }

        public void SetAccessToken(string accessToken)
        {
            _accessToken = accessToken;
        }

        public virtual string PostData()
        {
            if (_requestParam == null)
                throw new Exception("参数不能为空");

            string openId = _requestParam.OpenId;
            if (string.IsNullOrEmpty(openId))
            {
                var dataAccess = BridgeHttpContext.DataAccess;
                var user = dataAccess.GetByParam<COM_USER>(new { ORGAN_ID = _requestParam.OrganId, USER_ID = _requestParam.UserId });
                if (user == null)
                {
                    throw new Exception("无此用户");
                }
                openId = user.OPEN_ID;
            }

            Data data = new Data();
            data.first = new First() { value = _requestParam.First };
            data.keyword1 = new Keyword1 { value = _requestParam.Keyword1 };
            data.keyword2 = new Keyword2 { value = _requestParam.Keyword2 };
            data.keyword3 = new Keyword3 { value = _requestParam.Keyword3 };
            data.keyword4 = new Keyword4 { value = _requestParam.Keyword4 };
            data.remark = new Remark { value = _requestParam.Remark };

            TemplateMessageModel messageModel = new TemplateMessageModel();
            messageModel.touser = openId;
            messageModel.template_id = "AhP-RdU9v68XAeBgj8FW7qjrSDfiEW6tCbBe2T5ZuLE";
            messageModel.url = _requestParam.CallbackUrl;
            messageModel.data = data;

            string jsonData = JsonUtil.JsonSerializeObject(messageModel);
            string url = string.Format(WeChatHttpUrl, AccessToken);
            string wcResult = HttpHelper.PostJson(url, jsonData);
            
            return wcResult;
        }
    }
}
